const utils = require("./utils");

const { WX_TOKEN, WX_APPID, WX_APPSECRET, WX_AESKEY } = process.env;

module.exports = {
  wxConfig: {
    token: WX_TOKEN,
    appId: WX_APPID,
    appSecret: WX_APPSECRET,
    encodingAESKey: WX_AESKEY,
  },
  listen(wxApp) {
    wxApp.subscribe(async (acc) => {
      acc.send.sendTxtMsg(
        `hi~我是收藏小助手，\n向我发送链接即可添加到${utils.getMpLink(
          "书签集",
          `/pages/index/index?mp_uid=${acc.fromUser}`
        )}`
      );
      const token = await acc.context.getAccessToken();
      const { unionid, subscribe_scene: scene } = await utils.getUserInfo(
        token,
        acc.fromUser
      );
      utils.onMpFollow({
        unionid,
        mp_uid: acc.fromUser,
        scene,
      });
    });
    wxApp.unsubscribe((acc) => {
      utils.onMpFollow({
        mp_uid: acc.fromUser,
      });
    });
    wxApp.text(/.+/, async (acc) => {
      let type = utils.isLink(acc.content, true) ? "link" : "note";
      if (acc.content == "【收到不支持的消息类型，暂无法显示】") {
        type = "";
      }
      this.onReply(acc, type);
    });
    const mediaList = ["image", "voice", "video", "link", "location"];
    for (const type of mediaList) {
      wxApp[type]((acc) => {
        this.onReply(acc, type);
      });
    }
  },

  onReply(acc, type) {
    // console.log(type);
    const sendMsg = acc.send.sendTxtMsg;
    if (!type) {
      // sendMsg("暂未支持此消息类型");
      // return;
    }
    if (type == "video") {
      // sendMsg("暂未支持视频收藏");
      // return;
    }
    utils.saveMsg(acc, type); // 经测试，似乎无法使用await等待保存后回复消息
    let name = {
      note: "笔记",
      link: "链接",
      location: "位置",
      voice: "语音",
      image: "图片",
      video: "视频",
    }[type];
    let path = `/pages/link/bundle?guid=${acc.fromUser}&msg_time=${acc.createTime}`;
    let msg = `暂未支持${name}消息`;
    if (type == "link") {
      name = `已收藏${name}`;
    } else {
      path = "/pages/index/index";
      name = "加入笔记(开发中)";
    }
    msg = utils.getMpLink(name, path);
    sendMsg(msg);
  },
};
